Renewable energy sources play an increasingly important role in the global energy mix, as the effort to reduce the environmental impact of energy production increases.
Out of all the renewable energy alternatives, wind energy is one of the most developed technologies worldwide. The U.S Department of Energy has put together a guide to achieving operational efficiency using predictive maintenance practices.
Predictive maintenance uses sensor information and analysis methods to measure and predict degradation and future component capability. The idea behind predictive maintenance is that failure patterns are predictable and if component failure can be predicted accurately and the component is replaced before it fails, the costs of operation and maintenance will be much lower.
The sensors fitted across different machines involved in the process of energy generation collect data related to various environmental factors (temperature, humidity, wind speed, etc.) and additional features related to various parts of the wind turbine (gearbox, tower, blades, break, etc.).
“ReneWind” is a company working on improving the machinery/processes involved in the production of wind energy using machine learning and has collected data of generator failure of wind turbines using sensors. They have shared a ciphered version of the data, as the data collected through sensors is confidential (the type of data collected varies with companies). Data has 40 predictors, 20000 observations in the training set and 5000 in the test set.
The objective is to build various classification models, tune them, and find the best one that will help identify failures so that the generators could be repaired before failing/breaking to reduce the overall maintenance cost. The nature of predictions made by the classification model will translate as follows:
True positives (TP) are failures correctly predicted by the model. These will result in repairing costs. False negatives (FN) are real failures where there is no detection by the model. These will result in replacement costs. False positives (FP) are detections where there is no failure. These will result in inspection costs. It is given that the cost of repairing a generator is much less than the cost of replacing it, and the cost of inspection is less than the cost of repair.
“1” in the target variables should be considered as “failure” and “0” represents “No failure”.
The data provided is a transformed version of original data which was collected using sensors. Train.csv - To be used for training and tuning of models. Test.csv - To be used only for testing the performance of the final best model. Both the datasets consist of 40 predictor variables and 1 target variable
!pip install --upgrade pandas==2.0.3
# Installing the libraries with the specified version.
!pip install numpy==1.25.2 pandas==2.0.3 scikit-learn==1.2.2 matplotlib==3.7.1 seaborn==0.13.1 xgboost==2.0.3 -q
pd.set_option('display.max_rows', None)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import (
f1_score,
accuracy_score,
recall_score,
precision_score,
confusion_matrix,
roc_auc_score,
make_scorer,
ConfusionMatrixDisplay,
)
from sklearn import metrics
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder
from sklearn.impute import SimpleImputer
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import RandomizedSearchCV
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import (
AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier, BaggingClassifier
)
from xgboost import XGBClassifier
import warnings
warnings.filterwarnings("ignore")
data = pd.read_csv("//content/drive/MyDrive/Train.csv.csv" )
data1 = pd.read_csv("/content/drive/MyDrive/Test.csv.csv")
data.head().T
data1.head().T
data.tail().T
data1.tail().T
data.shape
There are 20,000 rows and 41 columns in the train set.
data1.shape
There are 5000 rows and 41 columns in the Test set.
data.info()
There are forty-one numeric columns( one integer and forty float type).
There are null values both in V1 and V2 in the dataset.
data1.info()
There are forty-one numeric columns( one integer and forty float type).
There are null values both in V1 and V2 in the dataset.
data.columns
data1.columns
There are forty one columns in both the train and test sets, forty have independent variable, and one has dependent variable.
data.describe(include='all').T
data1.describe(include='all').T
print(data.duplicated().sum())
print(data1.duplicated().sum())
print(data.isna().sum())
print(data1.isna().sum())
df = data.copy()
df1 = data1.copy()
# function to plot a boxplot and a histogram along the same scale.
def histogram_boxplot(data, feature, figsize=(12, 7), kde=False, bins=None):
"""
Boxplot and histogram combined
data: dataframe
feature: dataframe column
figsize: size of figure (default (12,7))
kde: whether to the show density curve (default False)
bins: number of bins for histogram (default None)
"""
f2, (ax_box2, ax_hist2) = plt.subplots(
nrows=2, # Number of rows of the subplot grid= 2
sharex=True, # x-axis will be shared among all subplots
gridspec_kw={"height_ratios": (0.25, 0.75)},
figsize=figsize,
) # creating the 2 subplots
sns.boxplot(
data=data, x=feature, ax=ax_box2, showmeans=True, color="violet"
) # boxplot will be created and a star will indicate the mean value of the column
sns.histplot(
data=data, x=feature, kde=kde, ax=ax_hist2, bins=bins, palette="winter"
) if bins else sns.histplot(
data=data, x=feature, kde=kde, ax=ax_hist2
) # For histogram
ax_hist2.axvline(
data[feature].mean(), color="green", linestyle="--"
) # Add mean to the histogram
ax_hist2.axvline(
data[feature].median(), color="black", linestyle="-"
) # Add median to the histogram
Plotting histograms and boxplots for all the variables
for feature in df.columns:
histogram_boxplot(data, feature, figsize=(12, 7), kde=False, bins=None)
for feature in df1.columns:
histogram_boxplot(data, feature, figsize=(12, 7), kde=False, bins=None)
Most of the independent variables in the train and test set are almost normaly distributed, but a few of them slightly skewed to the right or left.
The Target variable which is either failure('1') or No-failure( 0') in both train and test dataset has more of No-failure than failure. Its distribution is densely populated at 'No-failure'.
Variables in train and test data have outliers to the both sides of their distribution plot.
There are outliers at both sides of the plot which may suggest positive and negative extreme values.
# Univariate Analysis
plt.figure(figsize=(10, 6))
sns.countplot(x='Target', data=df)
plt.title('Target Variable Distribution')
plt.show()
# Univariate Analysis
plt.figure(figsize=(10, 6))
sns.countplot(x='Target', data=df1)
plt.title('Target Variable Distribution')
plt.show()
## Function to plot distributions
def distribution_plot_wrt_target(data, predictor, target):
fig, axs = plt.subplots(2, 2, figsize=(12, 10))
target_uniq = data[target].unique()
axs[0, 0].set_title("Distribution of target for target=" + str(target_uniq[0]))
sns.histplot(
data=data[data[target] == target_uniq[0]],
x=predictor,
kde=True,
ax=axs[0, 0],
color="teal",
)
axs[0, 1].set_title("Distribution of target for target=" + str(target_uniq[1]))
sns.histplot(
data=data[data[target] == target_uniq[1]],
x=predictor,
kde=True,
ax=axs[0, 1],
color="orange",
)
axs[1, 0].set_title("Boxplot w.r.t target")
sns.boxplot(data=data, x=target, y=predictor, ax=axs[1, 0], palette="gist_rainbow")
axs[1, 1].set_title("Boxplot (without outliers) w.r.t target")
sns.boxplot(
data=data,
x=target,
y=predictor,
ax=axs[1, 1],
showfliers=False,
palette="gist_rainbow",
)
plt.tight_layout()
plt.show()
# the values of target variable in the train set
df["Target"].value_counts()
# the values of target variable in the test set
df1["Target"].value_counts()
Correlation check among numerical variables
# Generate a sample dataframe with 40 independent variables and 1 target variable
np.random.seed(42)
num_samples = 100 # You can adjust the number of samples
data = pd.DataFrame(np.random.rand(num_samples, 40), columns=[f'V{i}' for i in range(1, 41)])
data['Target'] = np.random.rand(num_samples)
# Calculate the correlation matrix
correlation_matrix = data.corr()
# Specify the columns for the different parts
variables_part1 = ['Target'] + [f'V{i}' for i in range(1, 21)]
variables_part2 = ['Target'] + [f'V{i}' for i in range(21, 41)]
variables_part3_x = [f'V{i}' for i in range(1, 21)]
variables_part3_y = [f'V{i}' for i in range(21, 41)]
# Create correlation matrices for each part
correlation_matrix_part1 = correlation_matrix.loc[variables_part1, variables_part1]
correlation_matrix_part2 = correlation_matrix.loc[variables_part2, variables_part2]
correlation_matrix_part3 = correlation_matrix.loc[variables_part3_x, variables_part3_y]
# Define a helper function to plot heatmaps
def plot_heatmap(matrix, title, cmap, filename):
plt.figure(figsize=(12, 10))
sns.heatmap(matrix, annot=True, cmap=cmap, fmt=".2f", annot_kws={"size": 10})
plt.xticks(rotation=45, ha='right', fontsize=12)
plt.yticks(rotation=0, fontsize=12)
plt.title(title, fontsize=14)
plt.tight_layout()
plt.savefig(filename)
plt.show()
# Plot each part separately with readable colors and increased font size
plot_heatmap(correlation_matrix_part1, 'Correlation Matrix - Part 1 (Target and V1 to V20)', 'coolwarm', 'part1_heatmap.png')
plot_heatmap(correlation_matrix_part2, 'Correlation Matrix - Part 2 (Target and V21 to V40)', 'viridis', 'part2_heatmap.png')
plot_heatmap(correlation_matrix_part3, 'Correlation Matrix - Part 3 (V1 to V20 vs V21 to V40)', 'Spectral', 'part3_heatmap.png')
'V5', 'V8', 'V9', 'V10', 'V12', 'V16', 'V18', 'V22', 'V23', 'V25', 'V27', 'V33', and 'V39' show weak but positive relationship with the target variable.
We shall further analyze their relationship using distribution plot.
Though there are positive relationship among a few independent variables, their correlations are not strong.
# Define independent variables that are positively correlated to 'Target'
dv = ['V5', 'V8', 'V9', 'V10', 'V12', 'V16', 'V18', 'V22', 'V23', 'V25', 'V27', 'V33', 'V39']
for variable in dv:
distribution_plot_wrt_target(df, variable, "Target")
The target variable (represented by the y-axis) has different distributions for the two x-axis values (0 and 1).
The median difference suggests that the relationship between these independent variables and the target variable varies depending on the x-axis value.
The presence of outliers indicates potential extreme values or anomalies in the data.
Further statistical analysis, such as hypothesis testing or regression modeling, could provide additional insights into the relationship between v5 and the target variable.
# Encode the target variable
label_encoder = LabelEncoder()
df['Target'] = label_encoder.fit_transform(df['Target'])
# Prepare data for modeling
X = df.drop(columns=['Target'])
y = df['Target']
X_test = df1.drop(columns=['Target'], errors='ignore')
print("Class distribution in target variable:")
class_counts = y.value_counts()
print(class_counts)
for class_label in y.unique():
class_count = (y == class_label).sum()
if class_count < 2:
print(f"Class {class_label} has only {class_count} instances, can't use stratify.")
# Remove the single instance class
X = X[y != class_label]
y = y[y != class_label]
print(f"Class {class_label} removed from the dataset")
We have no need to split the dataset into train and test data since we are already given.
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, stratify=y, random_state=1)
print(X_train.shape, X_val.shape, X_test.shape)
*The splitted dataset has train set with 16000rows and 40 columns; validation set with 4000 rows and 40 columns, and test set with 5000 rows and 4o columns.
# defining a list with names of columns that will be used for imputation in Train set
reqd_col_for_impute = ['V1','V2']
df[reqd_col_for_impute].head()
# defining a list with names of columns that will be used for imputation in Test set
df1[reqd_col_for_impute].head()
# Initialize the SimpleImputer with the strategy to replace missing values with the median
imputer = SimpleImputer(strategy='median')
# Fit and transform the data with the imputer to impute missing values
X_imputed = imputer.fit_transform(X_train)
# Fit and transform the train data
X_train[reqd_col_for_impute] = imputer.fit_transform(X_train[reqd_col_for_impute])
# Transform the validation data
X_val[reqd_col_for_impute] = imputer.transform(X_val[reqd_col_for_impute])
# Transform the test data
X_test[reqd_col_for_impute] = imputer.transform(X_test[reqd_col_for_impute])
# Checking that no column has missing values in train, validation or test sets
print(X_train.isna().sum())
print("-" * 30)
print(X_val.isna().sum())
print("-" * 30)
print(X_test.isna().sum())
# Verifying the shapes of the imputed data
print("X_train_imputed shape:", X_train.shape)
print("X_val_imputed shape:", X_val.shape)
print("X_test_imputed shape:", X_test.shape)
# Generate a sample dataframe with 40 independent variables and 1 target variable
np.random.seed(42)
num_samples = 100 # You can adjust the number of samples
data = pd.DataFrame(np.random.rand(num_samples, 40), columns=[f'V{i}' for i in range(1, 41)])
data['Target'] = np.random.rand(num_samples)
# Calculate the correlation matrix
correlation_matrix = data.corr()
# Specify the columns for the different parts
variables_part1 = ['Target'] + [f'V{i}' for i in range(1, 21)]
variables_part2 = ['Target'] + [f'V{i}' for i in range(21, 41)]
variables_part3_x = [f'V{i}' for i in range(1, 21)]
variables_part3_y = [f'V{i}' for i in range(21, 41)]
# Create correlation matrices for each part
correlation_matrix_part1 = correlation_matrix.loc[variables_part1, variables_part1]
correlation_matrix_part2 = correlation_matrix.loc[variables_part2, variables_part2]
correlation_matrix_part3 = correlation_matrix.loc[variables_part3_x, variables_part3_y]
# Define a helper function to plot heatmaps
def plot_heatmap(matrix, title, cmap, filename):
plt.figure(figsize=(12, 10))
sns.heatmap(matrix, annot=True, cmap=cmap, fmt=".2f", annot_kws={"size": 10})
plt.xticks(rotation=45, ha='right', fontsize=12)
plt.yticks(rotation=0, fontsize=12)
plt.title(title, fontsize=14)
plt.tight_layout()
plt.savefig(filename)
plt.show()
# Plot each part separately with readable colors and increased font size
plot_heatmap(correlation_matrix_part1, 'Correlation Matrix - Part 1 (Target and V1 to V20)', 'coolwarm', 'part1_heatmap.png')
plot_heatmap(correlation_matrix_part2, 'Correlation Matrix - Part 2 (Target and V21 to V40)', 'viridis', 'part2_heatmap.png')
plot_heatmap(correlation_matrix_part3, 'Correlation Matrix - Part 3 (V1 to V20 vs V21 to V40)', 'Spectral', 'part3_heatmap.png')
The nature of predictions made by the classification model will translate as follows:
1.True positives (TP) are failures correctly predicted by the model.
2.False negatives (FN) are real failures in a generator where there is no detection by model.
3.False positives (FP) are failure detections in a generator where there is no failure.
We need to choose the metric which will ensure that the maximum number of generator failures are predicted correctly by the model. We would want Recall to be maximized as greater the Recall, the higher the chances of minimizing false negatives. We want to minimize false negatives because if a model predicts that a machine will have no failure when there will be a failure, it will increase the maintenance cost.
# Type of scoring used to compare parameter combinations
scorer = metrics.make_scorer(metrics.recall_score)
Let's define a function to output different metrics (including recall) on the train and test set and a function to show confusion matrix so that we do not have to use the same code repetitively while evaluating models.
# defining a function to compute different metrics to check performance of a classification model built using sklearn
def model_performance_classification_sklearn(model, predictors, target):
"""
Function to compute different metrics to check classification model performance
model: classifier
predictors: independent variables
target: dependent variable
"""
# predicting using the independent variables
pred = model.predict(predictors)
acc = accuracy_score(target, pred) # to compute Accuracy
recall = recall_score(target, pred) # to compute Recall
precision = precision_score(target, pred) # to compute Precision
f1 = f1_score(target, pred) # to compute F1-score
# creating a dataframe of metrics
df_perf = pd.DataFrame(
{
"Accuracy": acc,
"Recall": recall,
"Precision": precision,
"F1": f1
},
index=[0],
)
return df_perf
def confusion_matrix_sklearn(model, predictors, target):
"""
To plot the confusion_matrix with percentages
model: classifier
predictors: independent variables
target: dependent variable
"""
y_pred = model.predict(predictors)
cm = confusion_matrix(target, y_pred)
labels = np.asarray(
[
["{0:0.0f}".format(item) + "\n{0:.2%}".format(item / cm.flatten().sum())]
for item in cm.flatten()
]
).reshape(2, 2)
plt.figure(figsize=(6, 4))
sns.heatmap(cm, annot=labels, fmt="")
plt.ylabel("True label")
plt.xlabel("Predicted label")
We want to reduce false negatives and will try to maximize "Recall".
To maximize Recall, we can use Recall as a scorer in cross-validation and hyperparameter tuning.
# Empty list to store all the models
models = []
# Appending initial models into the list
models.append(("Logistic Regression", LogisticRegression(random_state=1)))
models.append(("Bagging", BaggingClassifier(random_state=1)))
models.append(("Random Forest", RandomForestClassifier(random_state=1)))
models.append(("Gradient Boosting", GradientBoostingClassifier(random_state=1)))
models.append(("AdaBoost", AdaBoostClassifier(random_state=1)))
models.append(("Decision Tree", DecisionTreeClassifier(random_state=1)))
models.append(("XGBoost", XGBClassifier(random_state=1,eval_metric="logloss")))
results1 = [] # Empty list to store all models' CV scores
names = [] # Empty list to store name of the models
# Define the scorer for model evaluation (e.g., recall score)
scorer = 'recall'
# Loop through all models to get the mean cross-validated score
print("\nCross-Validation performance on the training dataset:\n")
for name, model in models:
kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=1) # Setting number of splits equal to 5
cv_result = cross_val_score(estimator=model, X=X_train, y=y_train, scoring=scorer, cv=kfold)
results1.append(cv_result)
names.append(name)
print("{}: {}".format(name, cv_result.mean()))
print("\nValidation Performance:\n")
# For evaluation on the validation dataset (X_val and y_val)
for name, model in models:
model.fit(X_train, y_train)
scores = recall_score(y_val, model.predict(X_val))
print("{}: {}".format(name, scores))
# Plotting boxplots for CV scores of all models defined above
fig = plt.figure(figsize=(10, 7))
fig.suptitle("Algorithm Comparison")
ax = fig.add_subplot(111)
plt.boxplot(results1)
ax.set_xticklabels(names)
plt.show()
print("Before OverSampling, counts of label '1': {}".format(sum(y_train == 1)))
print("Before OverSampling, counts of label '0': {} \n".format(sum(y_train == 0)))
# Synthetic Minority Over Sampling Technique
sm = SMOTE(sampling_strategy=1, k_neighbors=5, random_state=1)
X_train_over, y_train_over = sm.fit_resample(X_train, y_train)
print("After OverSampling, counts of label '1': {}".format(sum(y_train_over == 1)))
print("After OverSampling, counts of label '0': {} \n".format(sum(y_train_over == 0)))
print("After OverSampling, the shape of train_X: {}".format(X_train_over.shape))
print("After OverSampling, the shape of train_y: {} \n".format(y_train_over.shape))
models = [] # Empty list to store all the models
# Appending models into the list
models.append(("Bagging", BaggingClassifier(random_state=1)))
models.append(("Random forest", RandomForestClassifier(random_state=1)))
models.append(("GBM", GradientBoostingClassifier(random_state=1)))
models.append(("Adaboost", AdaBoostClassifier(random_state=1)))
models.append(("Xgboost", XGBClassifier(random_state=1, eval_metric="logloss")))
models.append(("dtree", DecisionTreeClassifier(random_state=1)))
results1 = [] # Empty list to store all model's CV scores
names = [] # Empty list to store name of the models
# Evaluate models using cross-validation on oversampled data
print("\nCross-validation performance on oversampled training dataset:\n")
for name, model in models:
kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
cv_result = cross_val_score(estimator=model, X=X_train_over, y=y_train_over, scoring="recall", cv=kfold)
results1.append(cv_result)
names.append(name)
print(f"{name}: {cv_result.mean()}")
# Fit models on the entire oversampled training data
print("\nValidation performance on oversampled validation dataset:\n")
for name, model in models:
model.fit(X_train_over, y_train_over)
scores = recall_score(y_val, model.predict(X_val))
print(f"{name}: {scores}")
# Plotting boxplots for CV scores of all models
fig = plt.figure(figsize=(10, 7))
fig.suptitle("Algorithm Comparison")
ax = fig.add_subplot(111)
plt.boxplot(results1)
ax.set_xticklabels(names)
plt.ylabel('Recall Score')
plt.show()
1.Random Forest and Xgboost still maintain their positions as top performers, demonstrating robustness even on the oversampled dataset.
2.The oversampling technique seems to have positively impacted GBM's performance, bringing it closer to the top performers.
3.Bagging and Adaboost show a noticeable drop in performance on the oversampled validation dataset compared to their training performance, suggesting potential overfitting or sensitivity to the changed data distribution.
4.The decision tree's complete failure to perform on the oversampled validation set indicates a critical issue with its ability to generalize to the modified dataset.
rus = RandomUnderSampler(random_state=1, sampling_strategy=1)
X_train_under, y_train_under = rus.fit_resample(X_train, y_train)
print("Before UnderSampling, counts of label '1': {}".format(sum(y_train == 1)))
print("Before UnderSampling, counts of label '0': {} \n".format(sum(y_train == 0)))
print("After UnderSampling, counts of label '1': {}".format(sum(y_train_under == 1)))
print("After UnderSampling, counts of label '0': {} \n".format(sum(y_train_under == 0)))
print("After UnderSampling, the shape of train_X: {}".format(X_train_under.shape))
print("After UnderSampling, the shape of train_y: {} \n".format(y_train_under.shape))
models = [] # Empty list to store all the models
# Appending models into the list
models.append(("Bagging", BaggingClassifier(random_state=1)))
models.append(("Random forest", RandomForestClassifier(random_state=1)))
models.append(("GBM", GradientBoostingClassifier(random_state=1)))
models.append(("Adaboost", AdaBoostClassifier(random_state=1)))
models.append(("Xgboost", XGBClassifier(random_state=1, eval_metric="logloss")))
models.append(("dtree", DecisionTreeClassifier(random_state=1)))
results11 = [] # Empty list to store all model's CV scores
names = [] # Empty list to store name of the models
# loop through all models to get the mean cross validated score
print("\n" "Cross-Validation performance on training dataset:" "\n")
for name, model in models:
kfold = StratifiedKFold(
n_splits=5, shuffle=True, random_state=1
) # Setting number of splits equal to 5
cv_result = cross_val_score(
estimator=model, X=X_train_under, y=y_train_under, scoring=scorer, cv=kfold
) ## ode to build models on undersampled data
results11.append(cv_result)
names.append(name)
print("{}: {}".format(name, cv_result.mean()))
print("\n" "Validation Performance:" "\n")
for name, model in models:
model.fit(X_train_under, y_train_under) ## code to build models on undersampled data
scores = recall_score(y_val, model.predict(X_val))
print("{}: {}".format(name, scores))
# Boxplot for cross-validation scores
plt.figure(figsize=(12, 8))
plt.boxplot(results11, labels=names)
plt.title('Cross-Validation Scores for Different Models')
plt.xlabel('Models')
plt.ylabel('Cross-Validation Score')
plt.xticks(rotation=45)
plt.show()
Random Forest, GBM, and Xgboost consistently show strong performance on both training and validation sets, suggesting good generalization.
Potential Overfitting: Decision Tree, while performing well on the training set, shows a significant drop in performance on the validation set, indicating potential overfitting.
We may likely consider focusing on Random Forest, GBM, or Xgboost for further tuning and evaluation, as they demonstrate a balance between strong performance and generalization.
Conclusion on models to tune based on the cross validation performance and validation performance.
1.High validation performance relative to training performance to ensure good generalization.
2.Consistent performance across both oversampled and undersampled datasets.
3.Models showing significant potential for improvement through hyperparameter tuning.
XGBoost, GBM, and Bagging models are preferred to be tuned because
*XGBoost shows the highest potential in terms of cross-validation performance on the oversampled data. While there's a performance drop in validation for the oversampled data, it maintains high validation scores with undersampled data, suggesting better generalization.
*GBM shows strong and consistent performance across both validation datasets.
*Bagging shows robust performance with undersampled data, indicating good generalization. Its performance discrepancy between training and validation on oversampled data suggests potential improvement through tuning and perhaps modifying the base estimator.
2.Decision Trees are prone to overfitting, especially with smaller datasets or when not pruned effectively. The high variability in performance indicates that the Decision Tree might be capturing noise in the training data, leading to poor generalization.
3.While AdaBoost improves performance by focusing on difficult-to-classify samples, it might still fall short in terms of overall model complexity and generalization.
.We will tune XGBoost, Bagging, and GBM models using GridSearchCV and RandomizedSearchCV.
##Hyperparameter Tuning using Oversampled data
%%time
# Define the XGBoost model
model = XGBClassifier(random_state=1, eval_metric='logloss')
# Parameter grid to pass in GridSearchCV
param_grid = {
'scale_pos_weight': [5, 10],
'gamma': [0, 3, 5],
'subsample': [0.8, 0.9],
'n_estimators': [150,200,250],
'learning_rate': [0.1, 0.2],
}
# Type of scoring used to compare parameter combinations
scorer = make_scorer(recall_score)
# Calling GridSearchCV
grid_cv = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scorer, cv=5, n_jobs=-1)
# Fitting parameters in GridSearchCV
grid_cv.fit(X_train_over, y_train_over)
print("Best Parameters: {}\nScore: {}".format(grid_cv.best_params_, grid_cv.best_score_))
# Creating new pipeline with best parameters
tuned_xgb1 = XGBClassifier(
scale_pos_weight=10,
gamma=0,
subsample=0.8,
n_estimators=200,
learning_rate=0.1,
)
tuned_xgb1.fit(X_train_over, y_train_over)
#check the performance on Training set
xgb1_train_perf = model_performance_classification_sklearn(tuned_xgb1, X_train_over, y_train_over)## the code to check the performance on undersampled train set
print("Training performance:")
xgb1_train_perf
# Calculating different metrics on validation set
xgb1_val_perf = model_performance_classification_sklearn(tuned_xgb1, X_val, y_val)
print("Validation performance:")
xgb1_val_perf
# creating confusion matrix
confusion_matrix_sklearn(tuned_xgb1, X_val, y_val)
1.The XGBoost model performed exceptionally on the training set, fails to generalize to the validation set, particularly in identifying the positive class.
2.The high false negative rate on the validation set (6 FN) significantly impacts recall, precision, and F1 scores.
1.XGBoost model performs exceptionally well on the training set with nearly perfect metrics.
2.There is a notable discrepancy when validating on unseen data. The lower validation recall indicates the model may not be generalizing well, particularly in identifying positive cases, as demonstrated by the high number of false negatives.
%time
# defining model
Model = XGBClassifier(random_state=1,eval_metric='logloss')
#Parameter grid to pass in RandomSearchCV
param_grid={ 'n_estimators': [150, 200, 250], 'scale_pos_weight': [5,10], 'learning_rate': [0.1,0.2], 'gamma': [0,3,5], 'subsample': [0.8,0.9] }
#Calling RandomizedSearchCV
randomized_cv = RandomizedSearchCV(estimator=Model, param_distributions=param_grid, n_iter=50, n_jobs = -1, scoring=scorer, cv=5, random_state=1)
#Fitting parameters in RandomizedSearchCV
randomized_cv.fit(X_train_over, y_train_over) ## the code to fit the model on over sampled data
print("Best parameters are {} with CV score={}:" .format(randomized_cv.best_params_,randomized_cv.best_score_))
# Creating new pipeline with best parameters
tuned_xgb2 = XGBClassifier(
scale_pos_weight=10,
gamma=5,
subsample=0.9,
n_estimators=200,
learning_rate=0.1,
)
tuned_xgb2.fit(X_train_over, y_train_over)
xgb2_train_perf = model_performance_classification_sklearn(tuned_xgb2, X_train_over, y_train_over) ##the code to check the performance on oversampled train set
print("Training performance:")
xgb2_train_perf
# Calculating different metrics on validation set
xgb2_val_perf = model_performance_classification_sklearn(tuned_xgb2, X_val, y_val)
print("Validation performance:")
xgb2_val_perf
# creating confusion matrix
confusion_matrix_sklearn(tuned_xgb2, X_val, y_val)
%%time
# Define theB agging model
model = BaggingClassifier(random_state=1)
# Parameter grid to pass in GridSearchCV
param_grid = {
'max_samples': [0.8, 0.9, 1],
'max_features': [0.7, 0.8, 0.9],
'n_estimators': [30, 50,70],
}
# Type of scoring used to compare parameter combinations
scorer = make_scorer(recall_score)
# Calling GridSearchCV
grid_cv = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scorer, cv=5, n_jobs=-1)
# Fitting parameters in GridSearchCV
grid_cv.fit(X_train_over, y_train_over)
print("Best Parameters: {}\nScore: {}".format(grid_cv.best_params_, grid_cv.best_score_))
# Creating new pipeline with best parameters
tuned_bag1 = BaggingClassifier(
max_samples=1,
max_features=0.7,
n_estimators=30
)
tuned_bag1.fit(X_train_over, y_train_over) # Fit the model on oversampled data
# check the performance on Training set
bag1_train_perf = model_performance_classification_sklearn(tuned_bag1, X_train_over, y_train_over)## the code to check the performance on undersampled train set
print("Training performance:")
bag1_train_perf
# Calculating different metrics on validation set
bag1_val_perf = model_performance_classification_sklearn(tuned_bag1, X_val, y_val)
print("Validation performance:")
bag1_val_perf
# creating confusion matrix
confusion_matrix_sklearn(tuned_bag1, X_val, y_val)
# defining model
Model = BaggingClassifier(random_state=1)
#Parameter grid to pass in RandomSearchCV
param_grid = { 'max_samples': [0.8,0.9,1], 'max_features': [0.7,0.8,0.9], 'n_estimators' : [30,50,70] }
#Calling RandomizedSearchCV
randomized_cv = RandomizedSearchCV(estimator=Model, param_distributions=param_grid, n_iter=50, n_jobs = -1, scoring=scorer, cv=5, random_state=1)
#Fitting parameters in RandomizedSearchCV
randomized_cv.fit(X_train_over, y_train_over) ## the code to fit the model on over sampled data
print("Best parameters are {} with CV score={}:" .format(randomized_cv.best_params_,randomized_cv.best_score_))
# Creating new pipeline with best parameters
tuned_bag2 = BaggingClassifier(
max_samples=1,
max_features=0.7,
n_estimators=30
)
tuned_bag2.fit(X_train_over, y_train_over) # Fit the model on oversampled data
# check the performance on Training set
bag2_train_perf = model_performance_classification_sklearn(tuned_bag2, X_train_over, y_train_over)## the code to check the performance on undersampled train set
print("Training performance:")
bag2_train_perf
# Calculating different metrics on validation set
bag2_val_perf = model_performance_classification_sklearn(tuned_bag2, X_val, y_val)
print("Validation performance:")
bag2_val_perf
# creating confusion matrix
confusion_matrix_sklearn(tuned_bag2, X_val, y_val)
%%time
# Define theB agging model
model =GradientBoostingClassifier(random_state=1)
# Parameter grid to pass in GridSearchCV
param_grid = {
"subsample": [0.5, 0.7],
"n_estimators": np.arange(100, 150, 25),
"learning_rate": [0.2, 0.05, 1],
"max_features": [0.5, 0.7]
}
# Type of scoring used to compare parameter combinations
scorer = make_scorer(recall_score)
# Calling GridSearchCV
grid_cv = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scorer, cv=5, n_jobs=-1)
# Fitting parameters in GridSearchCV
grid_cv.fit(X_train_over, y_train_over)
print("Best Parameters: {}\nScore: {}".format(grid_cv.best_params_, grid_cv.best_score_))
pass
pass
# Creating new pipeline with best parameters
tuned_gb1 = GradientBoostingClassifier(random_state=1)
{
"subsample": 0.7,
"n_estimators": 100,
"learning_rate": 0.2,
"max_features": 0.5
}
tuned_gb1.fit(X_train_over, y_train_over) # Fit the model on oversampled data
# check the performance on Training set
gb1_train_perf = model_performance_classification_sklearn(tuned_gb1, X_train_over, y_train_over)## the code to check the performance on oversampled train set
gb1_train_perf
# Calculating different metrics on validation set
gb1_val_perf = model_performance_classification_sklearn(tuned_gb1, X_val, y_val)
print("Validation performance:")
gb1_val_perf
## creating confusion matrix
confusion_matrix_sklearn(tuned_gb1, X_val, y_val)
%%time
# Define the GradientBoosting model
model = GradientBoostingClassifier(random_state=1)
# Parameter grid to pass in RandomizedSearchCV
param_grid = {
"n_estimators": np.arange(100, 150, 25),
"learning_rate": [0.2, 0.05, 1],
"subsample": [0.5, 0.7],
"max_features": [0.5, 0.7]
}
# Type of scoring used to compare parameter combinations
scorer = make_scorer(recall_score)
# Create the RandomizedSearchCV object
randomized_cv = RandomizedSearchCV(
estimator=model, # Corrected 'Model' to 'model'
param_distributions=param_grid,
n_iter=50,
n_jobs=-1,
scoring=scorer,
cv=5,
random_state=1
)
# Fitting parameters in RandomizedSearchCV
randomized_cv.fit(X_train_over, y_train_over) # Fit the model on oversampled data
# Output the best parameters and best CV score
print("Best parameters are {} with CV score={}:" .format(randomized_cv.best_params_, randomized_cv.best_score_))
# Creating a new instance of GradientBoostingClassifier with the best parameters
tuned_gb2 = GradientBoostingClassifier(
random_state=1,
n_estimators=100,
learning_rate=0.2,
subsample=0.7,
max_features=0.5
)
# Fit the model on the oversampled data
tuned_gb2.fit(X_train_over, y_train_over)
# check the performance on Training set
gb2_train_perf = model_performance_classification_sklearn(tuned_gb2, X_train_over, y_train_over)## the code to check the performance on undersampled train set
gb2_train_perf
# Calculating different metrics on validation set
gb2_val_perf = model_performance_classification_sklearn(tuned_gb2, X_val, y_val)
print("Validation performance:")
gb2_val_perf
# creating confusion matrix
confusion_matrix_sklearn(tuned_gb2, X_val, y_val)
%%time
# Define the XGBoost model
model = XGBClassifier(random_state=1, eval_metric='logloss')
# Parameter grid to pass in GridSearchCV
param_grid = {
'scale_pos_weight': [5, 10],
'gamma': [0, 3, 5],
'subsample': [0.8, 0.9],
'n_estimators': [150,200,250],
'learning_rate': [0.1, 0.2],
}
# Type of scoring used to compare parameter combinations
scorer = make_scorer(recall_score)
# Calling GridSearchCV
grid_cv = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scorer, cv=5, n_jobs=-1)
# Fitting parameters in GridSearchCV
grid_cv.fit(X_train_under, y_train_under)
print("Best Parameters: {}\nScore: {}".format(grid_cv.best_params_, grid_cv.best_score_))
# Creating new pipeline with best parameters
tuned_xgb3 = XGBClassifier(
scale_pos_weight=10,
gamma=5,
subsample=0.8,
n_estimators=150,
learning_rate=0.1,
eval_metric='logloss'
)
tuned_xgb3.fit(X_train_under, y_train_under) # Fit the model on undersampled data
#check the performance on Training set
xgb3_train_perf = model_performance_classification_sklearn(tuned_xgb3, X_train_under, y_train_under)## the code to check the performance on undersampled train set xgb_train_perf
xgb3_train_perf
# Calculating different metrics on validation set
xgb3_val_perf = model_performance_classification_sklearn(tuned_xgb3, X_val, y_val)
print("Validation performance:")
xgb3_val_perf
# creating confusion matrix
confusion_matrix_sklearn(tuned_xgb3, X_val, y_val)
%time
# defining model
Model = XGBClassifier(random_state=1,eval_metric='logloss')
#Parameter grid to pass in RandomSearchCV
param_grid={ 'n_estimators': [150, 200, 250], 'scale_pos_weight': [5,10], 'learning_rate': [0.1,0.2], 'gamma': [0,3,5], 'subsample': [0.8,0.9] }
#Calling RandomizedSearchCV
randomized_cv = RandomizedSearchCV(estimator=Model, param_distributions=param_grid, n_iter=50, n_jobs = -1, scoring=scorer, cv=5, random_state=1)
#Fitting parameters in RandomizedSearchCV
randomized_cv.fit(X_train_under, y_train_under) ## the code to fit the model on undersampled data
print("Best parameters are {} with CV score={}:" .format(randomized_cv.best_params_,randomized_cv.best_score_))
# Creating new pipeline with best parameters
tuned_xgb4 = XGBClassifier(
scale_pos_weight=10,
gamma=5,
subsample=0.8,
n_estimators=200,
learning_rate=0.1,
)
tuned_xgb4.fit(X_train_under, y_train_under)
#check the performance on Training set
xgb4_train_perf = model_performance_classification_sklearn(tuned_xgb4, X_train_under, y_train_under)## the code to check the performance on undersampled train set xgb_train_perf
xgb4_train_perf
# Calculating different metrics on validation set
xgb4_val_perf = model_performance_classification_sklearn(tuned_xgb4, X_val, y_val)
print("Validation performance:")
xgb4_val_perf
# creating confusion matrix
confusion_matrix_sklearn(tuned_xgb4, X_val, y_val)
%%time
# Define theB agging model
model = BaggingClassifier(random_state=1)
# Parameter grid to pass in GridSearchCV
param_grid = {
'max_samples': [0.8, 0.9, 1],
'max_features': [0.7, 0.8, 0.9],
'n_estimators': [30, 50,70],
}
# Type of scoring used to compare parameter combinations
scorer = make_scorer(recall_score)
# Calling GridSearchCV
grid_cv = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scorer, cv=5, n_jobs=-1)
# Fitting parameters in GridSearchCV
grid_cv.fit(X_train_under, y_train_under)
print("Best Parameters: {}\nScore: {}".format(grid_cv.best_params_, grid_cv.best_score_))
# Creating new pipeline with best parameters
tuned_bag3 = BaggingClassifier(
max_samples=0.8,
max_features=0.7,
n_estimators=70,
random_state=1
)
tuned_bag3.fit(X_train_under, y_train_under) # Fit the model on undersampled data
# check the performance on Training set
bag3_train_perf = model_performance_classification_sklearn(tuned_bag3, X_train_under, y_train_under)## the code to check the performance on undersampled train set
bag3_train_perf
# Calculating different metrics on validation set
bag3_val_perf = model_performance_classification_sklearn(tuned_bag3, X_val, y_val)
print("Validation performance:")
bag3_val_perf
## creating confusion matrix
confusion_matrix_sklearn(tuned_bag3, X_val, y_val)
%time
# defining model
Model = BaggingClassifier(random_state=1)
#Parameter grid to pass in RandomSearchCV
param_grid = { 'max_samples': [0.8,0.9,1], 'max_features': [0.7,0.8,0.9], 'n_estimators' : [30,50,70], }
#Calling RandomizedSearchCV
randomized_cv = RandomizedSearchCV(estimator=Model, param_distributions=param_grid, n_iter=50, n_jobs = -1, scoring=scorer, cv=5, random_state=1)
#Fitting parameters in RandomizedSearchCV
randomized_cv.fit(X_train_under, y_train_under) ## the code to fit the model on undersampled data
print("Best parameters are {} with CV score={}.".format(randomized_cv.best_params_, randomized_cv.best_score_))
# Creating new pipeline with best parameters
tuned_bag4 = BaggingClassifier(
max_samples=0.8,
max_features=0.7,
n_estimators=70,
random_state=1
)
tuned_bag4.fit(X_train_under, y_train_under) # Fit the model on undersampled data
# check the performance on Training set
bag4_train_perf = model_performance_classification_sklearn(tuned_bag4, X_train_under, y_train_under)## the code to check the performance on undersampled train set
print("Training performance:")
bag4_train_perf
# Calculating different metrics on validation set
bag4_val_perf = model_performance_classification_sklearn(tuned_bag4, X_val, y_val)
print("Validation performance:")
bag4_val_perf
## creating confusion matrix
confusion_matrix_sklearn(tuned_bag4, X_val, y_val)
%%time
# Define theB agging model
model =GradientBoostingClassifier(random_state=1)
# Parameter grid to pass in GridSearchCV
param_grid = {
"subsample": [0.5, 0.7],
"n_estimators": np.arange(100, 150, 25),
"learning_rate": [0.2, 0.05, 1],
"max_features": [0.5, 0.7]
}
# Type of scoring used to compare parameter combinations
scorer = make_scorer(recall_score)
# Calling GridSearchCV
grid_cv = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scorer, cv=5, n_jobs=-1)
# Fitting parameters in GridSearchCV
grid_cv.fit(X_train_under, y_train_under)
print("Best Parameters: {}\nScore: {}".format(grid_cv.best_params_, grid_cv.best_score_))
# Creating a new instance of GradientBoostingClassifier with the best parameters
tuned_gb3 = GradientBoostingClassifier(
n_estimators=125,
learning_rate=0.2,
subsample=0.7,
max_features=0.5,
random_state=1
)
tuned_gb3.fit(X_train_under, y_train_under) # Fit the model on undersampled data
# check the performance on Training set
gb3_train_perf = model_performance_classification_sklearn(tuned_gb3, X_train_under, y_train_under)## the code to check the performance on undersampled train set
gb3_train_perf
# Calculating different metrics on validation set
gb3_val_perf = model_performance_classification_sklearn(tuned_gb3, X_val, y_val)
print("Validation performance:")
gb3_val_perf
## creating confusion matrix
confusion_matrix_sklearn(tuned_gb3, X_val, y_val)
%time
#defining model
Model = GradientBoostingClassifier(random_state=1)
#Parameter grid to pass in RandomSearchCV
param_grid = { "n_estimators": np.arange(100,150,25), "learning_rate": [0.2, 0.05, 1], "subsample":[0.5,0.7], "max_features":[0.5,0.7] }
randomized_cv = RandomizedSearchCV(estimator=Model, param_distributions=param_grid, n_iter=50, n_jobs = -1, scoring=scorer, cv=5, random_state=1)
#Fitting parameters in RandomizedSearchCV
randomized_cv.fit(X_train_under, y_train_under) ## the code to fit the model on undersampled data
print("Best parameters are {} with CV score={}:" .format(randomized_cv.best_params_,randomized_cv.best_score_))
# Creating a new instance of GradientBoostingClassifier with the best parameters
tuned_gb4 = GradientBoostingClassifier(
n_estimators=125,
learning_rate=0.2,
subsample=0.7,
max_features=0.5,
random_state=1
)
tuned_gb4.fit(X_train_under, y_train_under) # Fit the model on undersampled data
# check the performance on Training set
gb4_train_perf = model_performance_classification_sklearn(tuned_gb4, X_train_under, y_train_under)## the code to check the performance on undersampled train set
gb4_train_perf
# Calculating different metrics on validation set
gb4_val_perf = model_performance_classification_sklearn(tuned_gb4, X_val, y_val)
print("Validation performance:")
gb4_val_perf
## creating confusion matrix
confusion_matrix_sklearn(tuned_gb4, X_val, y_val)
We have now tuned all the models, let's compare the performance of all tuned models and see which one is the best.
# Training Performance
# Concatenate the DataFrames for training performance comparison
models_train_comp_df = pd.concat(
[
gb1_train_perf.T, # Gradient Boosting with GridSearch (Oversampled)
gb2_train_perf.T, # Gradient Boosting with RandomSearch (Oversampled)
xgb1_train_perf.T, # XGBoost with GridSearch (Oversampled)
xgb2_train_perf.T, # XGBoost with RandomSearch (Oversampled)
bag1_train_perf.T, # Bagging with GridSearch (Oversampled)
bag2_train_perf.T, # Bagging with RandomSearch (Oversampled)
gb3_train_perf.T, # Gradient Boosting with GridSearch (Undersampled)
gb4_train_perf.T, # Gradient Boosting with RandomSearch (Undersampled)
xgb3_train_perf.T, # XGBoost with GridSearch (Undersampled)
xgb4_train_perf.T, # XGBoost with RandomSearch (Undersampled)
bag3_train_perf.T, # Bagging with GridSearch (Undersampled)
bag4_train_perf.T, # Bagging with RandomSearch (Undersampled)
],
axis=1,
)
# Correct the columns naming
models_train_comp_df.columns = [
"Gradient Boosting tuned with oversampled data using GridSearch",
"Gradient Boosting tuned with oversampled data using RandomizedSearch",
"XGBoost tuned with oversampled data using GridSearch",
"XGBoost tuned with oversampled data using RandomizedSearch",
"Bagging tuned with oversampled data using GridSearch",
"Bagging tuned with oversampled data using RandomizedSearch",
"Gradient Boosting tuned with undersampled data using GridSearch",
"Gradient Boosting tuned with undersampled data using RandomizedSearch",
"XGBoost tuned with undersampled data using GridSearch",
"XGBoost tuned with undersampled data using RandomizedSearch",
"Bagging tuned with undersampled data using GridSearch",
"Bagging tuned with undersampled data using RandomizedSearch",
]
# Print the training performance comparison DataFrame
print("Training performance comparison:")
print(models_train_comp_df)
# Concatenate the DataFrames for validation performance comparison
models_val_comp_df = pd.concat(
[
gb1_val_perf.T, # Gradient Boosting with GridSearch (Oversampled)
gb2_val_perf.T, # Gradient Boosting with RandomSearch (Oversampled)
xgb1_val_perf.T, # XGBoost with GridSearch (Oversampled)
xgb2_val_perf.T, # XGBoost with RandomSearch (Oversampled)
bag1_val_perf.T, # Bagging with GridSearch (Oversampled)
bag2_val_perf.T, # Bagging with RandomSearch (Oversampled)
gb3_val_perf.T, # Gradient Boosting with GridSearch (Undersampled)
gb4_val_perf.T, # Gradient Boosting with RandomSearch (Undersampled)
xgb3_val_perf.T, # XGBoost with GridSearch (Undersampled)
xgb4_val_perf.T, # XGBoost with RandomSearch (Undersampled)
bag3_val_perf.T, # Bagging with GridSearch (Undersampled)
bag4_val_perf.T, # Bagging with RandomSearch (Undersampled)
],
axis=1,
)
# Correct the columns naming
models_val_comp_df.columns = [
"Gradient Boosting tuned with oversampled data using GridSearch",
"Gradient Boosting tuned with oversampled data using RandomizedSearch",
"XGBoost tuned with oversampled data using GridSearch",
"XGBoost tuned with oversampled data using RandomizedSearch",
"Bagging tuned with oversampled data using GridSearch",
"Bagging tuned with oversampled data using RandomizedSearch",
"Gradient Boosting tuned with undersampled data using GridSearch",
"Gradient Boosting tuned with undersampled data using RandomizedSearch",
"XGBoost tuned with undersampled data using GridSearch",
"XGBoost tuned with undersampled data using RandomizedSearch",
"Bagging tuned with undersampled data using GridSearch",
"Bagging tuned with undersampled data using RandomizedSearch",
]
# Print the validation performance comparison DataFrame
print("Validation performance comparison:")
print(models_val_comp_df)
1.XGBoost Tuned with Oversampled Data (using GridSearch):demonstrates excellent training performance and strong validation performance, indicating good generalization ability. However, the precision is noticeably impacted (0.732075) compared to recall (0.873874), but it remains a strong candidate given the overall high scores.
2.Gradient Boosting Tuned with Undersampled Data (using either GridSearch or RandomizedSearch):performs very well during training with undersampled data, its performance drops in validation, particularly in precision.
3.Bagging Tuned with Undersampled Data (using either GridSearch or RandomizedSearch):shows excellent training performance but relatively lower validation performance, especially in precision. While they have high recall, the precision drop impacts their F1-score.
4.Therefore, Based on the provided performance metrics, XGBoost tuned on oversampled data using GridSearch appears to be the best model.
*High Training Performance: It has very high training accuracy with excellent precision and recall, implying robust learning.
*Strong Validation Performance: Despite the drop from training to validation, the model maintains high validation accuracy (0.975250) and good F1-score (0.796715).
Our final model is tuned_xgb1(XGBoost on oversampled data using GridSerachCV).
Now we have our final model, so let's find out how our final model is performing on unseen test data.
# Define Test set
y_test = df1['Target']
X_test = df1.drop('Target', axis=1)
# Calculating different metrics on the test set
xgb1_test_perf = model_performance_classification_sklearn(tuned_xgb1, X_test, y_test) ##
print("Test performance:")
xgb1_test_perf
Observations
1.High Accuracy but Moderate Precision:While the model has high accuracy (97.4%), its precision (73.2%) is relatively lower. This indicates the model has a moderate number of false positives.
2.Good Recall:The recall of 85.1% suggests the model is fairly good at detecting actual positive instances, missing only 14.9% of positives.
3.Balanced F1-Score:The F1-score of 78.7% provides a single measure that balances precision and recall, showing that the model maintains reasonably good performance in both metrics without overly favoring one.
4.We can improve Precision by further tuning to reduce false positives might be beneficial. This could involve adjusting the classification threshold or using different algorithms or feature engineering strategies.
import xgboost as xgb
# training DataFrame with feature names
feature_names = X_train.columns
# Extract feature importances from the XGBoost model
importances = tuned_xgb1.feature_importances_
# Get the indices that would sort the array (ascending)
indices = np.argsort(importances)
# Plot the feature importances
plt.figure(figsize=(12, 12))
plt.title("Feature Importances")
plt.barh(range(len(indices)), importances[indices], color="violet", align="center")
plt.yticks(range(len(indices)), [feature_names[i] for i in indices])
plt.xlabel("Relative Importance")
plt.show()
**XGBoost model shows the relative importance of machineries or/and processes in failing.V36 and V22 have the highest and lowest relative importance respectively.
1.Now that we have a final model, let's use pipelines to put the model into production. We know that we can use pipelines to standardize the model building, but the steps in a pipeline are applied to each and every variable.
2.We use Column Transformer to personalize the pipeline to perform different preprocessing steps on different columns.
# Import necessary libraries for creating and saving the pipeline
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
import xgboost as xgb
import joblib
from sklearn.metrics import classification_report, accuracy_score, precision_score, recall_score, f1_score
import numpy as np
import matplotlib.pyplot as plt
# Define all numeric features
numeric_features = X_train.columns.tolist()
numeric_features
# We can't oversample/undersample data without doing missing value treatment, so let's first treat the missing values in the train set
imputer = SimpleImputer(strategy="median")
numeric_features = imputer.fit_transform(X1)
numeric_features
# We don't need to impute missing values in test set as it will be done inside pipeline
*tuned_xgb1 is already trained and considered the best model.
*Create a pipeline that includes the preprocessing step (StandardScaler) and the best XGBoost model (tuned_xgb1).
# Create the pipeline
Pipeline_model = Pipeline([
('scaler', StandardScaler()), # Preprocessing step to scale the features
('xgboost', tuned_xgb1) # Your best XGBoost model
])
# To fit the pipeline
Pipeline_model.fit(X_train, y_train)
# To make predictions on the test set
y_pred = Pipeline_model.predict(X_test)
y_pred
*Evaluate the pipeline model on various metrics: accuracy, precision, recall, and F1-score:
# Calculate the metrics
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='weighted')
recall = recall_score(y_test, y_pred, average='weighted')
f1 = f1_score(y_test, y_pred, average='weighted')
# Print the results
print(f"Accuracy of the final pipeline: {accuracy}")
print(f"Precision of the final pipeline: {precision}")
print(f"Recall of the final pipeline: {recall}")
print(f"F1 Score of the final pipeline: {f1}")
1.The high accuracy suggests that the model is suitable for real-world application and can be relied upon for both failure and non-failure predictions, reducing the risk of unnoticed failures and false alarms.
2.With high precision, the operational team can trust that when a warning for a potential failure is issued, it is likely to be a true failure. This helps in optimizing maintenance schedules and resource allocation, avoiding unnecessary checks and interventions.
3.The high recall ensures that most of the actual failures are flagged by the model, which is crucial for preventive maintenance strategies. This helps in reducing unexpected downtimes and potential dangers associated with component failures, thereby ensuring smooth operation of the wind energy installations.
4.The high F1 score reflects the model’s balanced capability in detecting failures accurately while minimizing missed failures. This is essential for maintaining operational efficiency and reducing costs associated with both undetected failures and false alerts.
def plot_feature_importances(pipeline, feature_names):
importances = pipeline.named_steps['xgboost'].feature_importances_
indices = np.argsort(importances)
plt.figure(figsize=(12, 12))
plt.title("Feature Importances")
plt.barh(range(len(indices)), importances[indices], color="violet", align="center")
plt.yticks(range(len(indices)), [feature_names[i] for i in indices])
plt.xlabel("Relative Importance")
plt.show()
# Plotting feature importances for the final model (optional)
plot_feature_importances(Pipeline_model, X_train.columns)
*XGBoost model with Oversampled data using GridSearchCV is the best model that can help improving the machinery/processes involved in the production of wind energy by detecting their failure or breakdown before it happens.
*The reasons why XGBoost model is the best are: 1.The high accuracy suggests that the model is suitable for real-world application and can be relied upon for both failure and non-failure predictions, reducing the risk of unnoticed failures and false alarms.
2.With high precision, the operational team can trust that when a warning for a potential failure is issued, it is likely to be a true failure. This helps in optimizing maintenance schedules and resource allocation, avoiding unnecessary checks and interventions.
3.The high recall ensures that most of the actual failures are flagged by the model, which is crucial for preventive maintenance strategies. This helps in reducing unexpected downtimes and potential dangers associated with component failures, thereby ensuring smooth operation of the wind energy installations.
4.The high F1 score reflects the model’s balanced capability in detecting failures accurately while minimizing missed failures. This is essential for maintaining operational efficiency and reducing costs associated with both undetected failures and false alerts.
*The importance features plot in the final model indicates from top-down their decreasing order of susceptible to failure and breakdown.
The relative importance of the features are represented in the plot above. V18 ,V29, and V3 are the first to third features with high relative importance. V8,V20, and V29 are the last three wind energy machinery and or procecesses that will fail .
5.Recommendations **Implement Preventive Maintenance Plans for components predicted to fail in order to minimize the risk of unexpected failures, reducing downtime, and extending the lifespan of components.
**Prioritize maintenance resources based on the model's predictions, focusing first on components with a high probability of failure. This practice will allow for efficient allocation of maintenance staff and resources, reducing costs and ensuring critical components are attended to promptly.
**Continuously monitor the predictions to detect any patterns or trends in component failurest o help in gaining deeper insights into common failure causes and improving the overall maintenance strategy.
**Use the failure predictions to adjust maintenance intervals dynamically, rather than following fixed schedules.This will lead to more effective use of resources and enhances the reliability of the wind energy components.
**Train the maintenance team to understand and act on model predictions. This is to ensure that they are well prepared to respond to and address potential failures accurately and efficiently.
**Integrate the XGBoost model into existing maintenance management systems for automated alerts and work order generation to streamlines the maintenance process and ensure timely interventions based on model predictions.
** Periodically retrain the model with new data to maintain its accuracy and relevance to ensure that the model adapts to any changes in data patterns or operational conditions, maintaining high performance.
**Use the feature importance scores from the XGBoost model to understand what factors contribute most to component failures.This will help your organization in providing actionable insights for design improvements, procurement decisions, and operation adjustments to mitigate failure risks.